package cn.lovelysia.ymcc.exception;

import cn.lovelysia.ymcc.enumcode.GlobalErrorCode;
import cn.lovelysia.ymcc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHander {

    /**
     * 自定义算术异常
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public JSONResult systemArithmeticException(){
        return JSONResult.error("算数异常","1001");
    }

    /**
     * 系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JSONResult systemException(Exception e){
        e.printStackTrace();//打印错误信息
        return JSONResult.error(GlobalErrorCode.SYSTEM_ERROR);
    }

    /**
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public JSONResult systemBusinessException(BusinessException e){
        e.printStackTrace();//打印错误信息
        return JSONResult.error(e.getMessage(),GlobalErrorCode.SYSTEM_ERROR.getCode());
    }

    /**
     * 添加数据
     *  JSR303
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult jsr303Exception(MethodArgumentNotValidException e){
        e.printStackTrace();//打印错误信息
        StringBuilder builder = new StringBuilder();
        //获取所有错误
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(err->{
            //err.getDefaultMessage();//取出每一个错误
            builder.append(err.getDefaultMessage()).append(";");
        });
        return JSONResult.error(builder.toString(),GlobalErrorCode.PARAM_ERROR.getCode());
    }
}
